<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      #father {
        background-color: antiquewhite;
        margin: 0 auto;
        padding: 10px;
        width: 300px;
      }
      #child {
        background-color: aquamarine;
        height: 100px;
      }
    </style>
  </head>
  <body>
    <div id="father">
      <div id="child"></div>
    </div>

    <script>
      const ws = new WeakSet();
      let parent = document.getElementById('father');
      let child = document.getElementById('child');

      function childListener(event) {
        console.log('child exist');
        event.stopPropagation();
      }

      function removeChild(event) {
        if (ws.has(child)) {
          this.removeChild(child);
          console.log(child); // 还保留着原先存着的对象内容
          console.log(document.getElementById('child')); // 此处已经获取不到了
          child = null; // 回收节点，否则引用还存在，弱引用没法清除
          console.log('child has removed!');
        } else {
          console.log('child has been removed!');
        }
      }

      child.addEventListener('click', childListener, false);
      parent.addEventListener('click', removeChild, false);

      ws.add(parent);
      ws.add(child);
      ws.add(childListener);
      console.log(ws);
    </script>
  </body>
</html>
